# -*- coding: utf-8 -*-
import os,zipfile
import shutil
from os.path import join 
class FileItem(object):
    def __init__(self,filename):
        self.filename=filename
        self.shortname=filename[len(os.path.dirname(filename))+1:]

    def zipto(self,path):
        """压缩文件到指定目录"""
        print 'zipto start'
        #if os.path.exists(path):
        #    os.remove(path)
        zip = zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED,allowZip64=True) 
        cutLen= len(os.path.dirname(self.filename))
        _sp=self.filename[cutLen:]
        zip.write(os.path.dirname(self.filename),_sp)   #创建空文件夹
        opfiles=[]
        file_num=0
        for root, dirs, files in os.walk(self.filename):   
            for name in files:
                try:
                    opfile=join(root,name)
                    print 'compressing ',opfile
                    #opfiles.append(opfile)
                    savepath=join(root[cutLen:],name)
                    zip.write(join(root ,name),savepath)
                except:
                    pass
            #for dir in dirs:
                #opfile=join(root,dir)
                #print 'compressing ',opfile
                #opfiles.append(opfile)
                #savepath=join(root[cutLen:],dir)
                #zip.write(join(root ,dir),savepath)
        #if not opfiles:
            #zip.write(os.path.dirname(self.filename))
        zip.close()
        print 'zipto end'
        return opfiles

    def exactto(self,path):
        """解压文件到指定目录"""
        if not os.path.exists(self.filename):
            raise Exception(self.filename + ' not found')
        if not os.path.exists(path):
            os.mkdir(path)
        zip=zipfile.ZipFile(self.filename,'r',zipfile.ZIP_DEFLATED,allowZip64=True) 
        zip.extractall(path)
        zip.close()

    def delete(self):
        if os.path.isfile(self.filename):
            os.remove(self.filename)
        elif os.path.isdir(self.filename):
            shutil.rmtree(self.filename)

    def decode_filename(self,filename):
        S_decode_list=['utf-8', 'gb2312', 'gbk', 'gb18030', 'cp1252', ]
        for coding in S_decode_list:
            try:
                data=filename.decode(coding)
                return data
            except:
                pass
        return ''
